package com.base;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.exception.ServiceException;
import com.res.UserRes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;


/**
 * @ClassName BaseController
 * @Description BaseController
 * @Author lxa
 * @Date 2019/1/24 20:21
 */
public class BaseController {
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());
    /**
     * 登录结果的 key
     */
    String SSO_TOKEN_KEY = "SSO_TOKEN";
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    /**
     * @author qiujunda
     * @date 2019年2月27日
     * @description 获取当前登录用户
     * @return
     */
    public UserRes getUser() {
        String ticket = this.getTicket();
        String result = redisTemplate.opsForValue().get(ticket);
        if (StringUtils.isBlank(result)) {
            throw new ServiceException("未登陆");
        }
        UserRes userRes = JSONObject.parseObject(result,new TypeReference<UserRes>(){});
        return userRes;
    }





    /**
     * 获取token
     *
     * @return
     */
    public String getTicket() {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes();
        HttpServletRequest servletRequest = servletRequestAttributes.getRequest();
        String ticket = null;
        if (StringUtils.isBlank(ticket)) {
            Cookie[] cookies = servletRequest.getCookies();// 这样便可以获取一个cookie数组
            if (null != cookies) {
                for (Cookie cookie : cookies) {
                    if (cookie.getName().equals(SSO_TOKEN_KEY)) {
                        ticket = cookie.getValue();
                        break;
                    }
                }
            }
        }
        if (StringUtils.isBlank(ticket)) {
            ticket = servletRequest.getParameter(SSO_TOKEN_KEY);
        }
        if (StringUtils.isBlank(ticket)) {
            ticket = servletRequest.getHeader(SSO_TOKEN_KEY);
        }

        if (StringUtils.isBlank(ticket)) {
            throw new ServiceException( "未登录");
        }
        return ticket;
    }


}
